<?php
class Admin_Index_Model extends NICED_Model
{
    public function isAdminUser($user_id)
    {
        require_once(DIR_LIBRARY."orm".DS."acl".DS."permission.php");
        $admin_user = new AclAdminUser();
        $admin_user->loadByUserId($user_id);

        return $admin_user->getField("user_id") ? true : false;
    }

    public function isLogin($session_id = NULL, $user_id = NULL)
    {
        if (SC::get("board_config.unnecessary_secondary_password"))
        {
            return true;
        }

        if (!$user_id)
        {
            $user_id    = Session::getUserId();
        }

        $bool = $this->isAdminUser($user_id);

        if (!$bool)
        {
            throw new NICED_Exception("not admin user");
        }

        require_once(DIR_LIBRARY."session.php");
        Session::start($session_id);

        return (Session::getAdminUserId()) ? true : false;
    }

    public function login($user_id, $password)
    {
        if (!$user_id)
        {
            throw new NICED_Exception("no user id for login admin");
        }

        require_once(DIR_LIBRARY."orm".DS."acl".DS."adminuser.php");
        $adminuser = AclAdminUser::factory();
        $adminuser->loadByUserId($user_id);

        if (!$adminuser->loaded)
        {
            throw new NICED_Exception("is not admin user");
        }

        $bool = self::checkPassword($password, $adminuser->getPassword());

        if (!$bool)
        {
            return false;
        }

        Session::setAdminUserId($user_id);

        return true;
    }

    private static function checkPassword($password_input, $password_from_db)
    {
        if ($password_from_db != md5($password_input))
        {
            throw new Exception("password incorrect");
        }

        return true;
    }

	public function loadUserMenu($user_id = 0)
	{
        if (!$user_id)
        {
            $user_id = Session::getUserId();
        }

        if (!$user_id)
        {
            throw new NICED_Exception("no user id for load menu");
        }

        require_once(DIR_LIBRARY."orm".DS."acl".DS."adminuser.php");
        $menu = AclAdminUser::getUserMenu($user_id);

        $this->set("menu", $menu);
	}

    public function loadAllMenu()
    {
        require_once(DIR_LIBRARY."orm".DS."acl".DS."access.php");
        $menu = AclAccess::getAllMenu();

        $this->set("menu", $menu);
    }
}//end class
